package sg.edu.ntu.metaweb.pastry;

import rice.p2p.commonapi.Application;
import rice.p2p.commonapi.Endpoint;
import rice.p2p.commonapi.Id;
import rice.p2p.commonapi.Message;
import rice.p2p.commonapi.Node;
import rice.p2p.commonapi.NodeHandle;
import rice.p2p.commonapi.RouteMessage;
import rice.tutorial.lesson4.MyMsg;
import sg.edu.ntu.metaweb.http.RequestHandler;

public class PastryApplication implements Application {

	protected Endpoint endpoint;
	protected Node node;
	public PastryNodeHandle pastryNodeHandle;
	public RequestHandler requestHandler;
	
	public PastryApplication(Node node, PastryNodeHandle pastryNodeHandle) {
		this.endpoint = node.buildEndpoint(this, "metaweb");
		this.node = node;
	    this.endpoint.register();
	    this.pastryNodeHandle = pastryNodeHandle;
	}
	
	public Node getNode() {
		return node;
	}
	  
	public void routeMyMsg(Id id, Message msg) {
	    endpoint.route(id, msg, null);
	}
	  
	public void routeMyMsgDirect(NodeHandle nh) {
	    Message msg = new MyMsg(endpoint.getId(), nh.getId());
	    endpoint.route(null, msg, nh);
	}
	    
	public void deliver(Id id, Message message) {
	    //System.out.println(this+" received "+message);
		pastryNodeHandle.messageHandler.handleMessage(message);
	}
	
	public void update(NodeHandle handle, boolean joined) {
	}
	  
	public boolean forward(RouteMessage message) {
	    return true;
	}
	  
}
